package no.ntnu.fp.gui;

import java.util.Calendar;



/**
 * A clock. If implemented as runnable, it will push the time each time the clock changes (1/minute).
 * @author Stephan
 *
 */
public class Clock implements Runnable{

	String theTime;
    Calendar now = Calendar.getInstance();
	ClockHolder pushTimeToMe;
	Thread myThread;
	boolean alive=true;
	
	
	/**
	 * Use this if you are not going to use the runnable methods. You 
	 * need to probe the clock to get the current time.
	 */
    public Clock(){
		
	}
	
    /**
     * The provided clockHolder supplied will receive the updated time automagicly.
     * @param i
     */
    public Clock(ClockHolder aClockHolder){
		pushTimeToMe = aClockHolder;
		myThread = new Thread(this);
		myThread.start();
	}
    
    /**
     * Use this method to get the current time. ("HH : MM")
     * @return
     */
	public String getTime(){
		if(now.get(Calendar.MINUTE)>9 && now.get(Calendar.HOUR_OF_DAY)>9){
			this.theTime = now.get(Calendar.HOUR_OF_DAY)+" : "+now.get(Calendar.MINUTE);
		}
		else if(now.get(Calendar.HOUR_OF_DAY)>9){
			this.theTime = now.get(Calendar.HOUR_OF_DAY)+" : 0"+now.get(Calendar.MINUTE);
		}
		else if(now.get(Calendar.MINUTE)>9){
			this.theTime = "0"+now.get(Calendar.HOUR_OF_DAY)+" : "+now.get(Calendar.MINUTE);
		}
		else{
			this.theTime = "0"+now.get(Calendar.HOUR_OF_DAY)+" : 0"+now.get(Calendar.MINUTE);
		}
		return this.theTime;
	}

	@Override
	public void run() {

		while(alive){
			now = Calendar.getInstance();
			pushTimeToMe.setTime(this.getTime());
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * Stop the running clock.
	 */
	public void stopRunningClock(){
		alive = false;
		
	}
	
	
	
}
